package learn.spring.gateway.config;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import learn.spring.gateway.entity.RolePermDto;
import learn.spring.gateway.service.IRolePermService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class LoadRolePermsData implements CommandLineRunner {

  @Autowired
  private IRolePermService rolePermService;

  public static final Map<String, List<String>> AUTH_MAP = new ConcurrentHashMap<>();

  @Override
  public void run(String... args) throws Exception {
    log.info("============================ LoadRolePermsData ");
    List<RolePermDto> rolePermDtos = rolePermService.listRolePerms();
    log.error("============= rolePermDtos {} ", rolePermDtos);
    for (RolePermDto dto : rolePermDtos) {
      if (!AUTH_MAP.containsKey(dto.getPermUrl())) {
        List<String> roleList = new ArrayList<>();
        roleList.add(dto.getRoleName());
        AUTH_MAP.put(dto.getPermUrl(), roleList);
      } else {
        AUTH_MAP.get(dto.getPermUrl()).add(dto.getRoleName());
      }
    }
//      权限和角色对应关系
//        AUTH_MAP.put("GET:/api/userInfo", "ROLE_ADMIN, ROLE_USER");
//        AUTH_MAP.put("GET:/api/hello", "GUEST");
    for (Map.Entry<String, List<String>> entry : AUTH_MAP.entrySet()) {
      log.error("===================entry.getKey {} ", entry.getKey());
      log.error("===================entry.getValue {} ", entry.getValue());
    }
  }
}
